import 'dart:ffi';
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:test01/okhttp_test/page/pages/okhttp_main.dart';
import 'package:test01/okhttp_test/pojo/attention_pojo.dart';
import 'package:test01/okhttp_test/util/request_http.dart';

void main() => runApp(
      MyApp(),
    );

class MyApp extends StatefulWidget {
  const MyApp({Key key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: CanvasTestPage(),
    );
  }
}

class CanvasTestPage extends StatefulWidget {
  const CanvasTestPage({Key key}) : super(key: key);

  @override
  _CanvasTestPageState createState() => _CanvasTestPageState();
}

class _CanvasTestPageState extends State<CanvasTestPage> {
  ///控制器
  ScrollController scrollController = ScrollController();

  ///定义接受数据的对象
  GetMyWigets getMyWigets = GetMyWigets();

  ///定义获取的体重列表
  List<GetRecordLists> getRecordList = [];

  ///判断是否到了最后数据
  bool isLast=false;


  int mm;

  @override
  void initState() {
    super.initState();
    //调用接口
    getUserWeight();
    //监听滚动到底部
    scrollController.addListener(() {
      if (scrollController.position.pixels == scrollController.position.maxScrollExtent) {
       if(isLast){
         print("==================后面没有数据拉==================");
       }else{
         //左拉加载更多
         getUserWeightRefresh();
       }
      }
    });
  }

  ///点击的范围
  Widget zz(int i,) {
    return Stack(
      children: <Widget>[
        Container(
          width: ((MediaQuery.of(context).size.width - 50 - 18) / 5),
          // 下边框
          decoration: BoxDecoration(
            color: Colors.primaries[i % Colors.primaries.length]
                .withOpacity(0.0),
          ),
          height: 300,
          // margin: EdgeInsets.only(left: 1),
        ),
       i==mm? Container(
         width: 50,
         height: 20,
         alignment: Alignment.center,
         margin: EdgeInsets.only(top:(224-(((((224/5)*5)-(224/5))/100) *
             (getRecordList[i].weight))>224?
         224-(((((224/5)*5)-(224/5))/100) * (getRecordList[i].weight))
             +12:224-(((((224/5)*5)-(224/5))/100) * (getRecordList[i].weight))-32),
             left: i==(getRecordList.length  - 1)?10:0
         ),
         decoration: BoxDecoration(
           border: Border.all(width: 0.5, color: Colors.red),
         ),
         child:Text("${getRecordList[i].weight}kg",style: TextStyle(fontSize: 12),),
       ):Container()
      ],
    );
  }

  ///调用用户记录体重的接口
  getUserWeight() async {
    getMyWigets = await getWeightRecords(
        interface: "/appuser/web/user/getWeightRecords", page: 1, size: 5);
    ///复制请求的页面
    getMyWigets.page=1;
    if (getMyWigets != null) {
      getMyWigets.recordList.forEach((element) {
        getRecordList.add(element);
        setState(() {});
      });
    }
  }


  ///刷新的数据
  getUserWeightRefresh() async {
    int page=getMyWigets.page+1;
    //定义数据列表为空
    GetMyWigets newGetMyWigets = GetMyWigets();
    newGetMyWigets = await getWeightRecords(
        interface: "/appuser/web/user/getWeightRecords", page:page, size: 5);
    //调取接口值
    if (newGetMyWigets != null) {
      //数组添加数据
      newGetMyWigets.recordList.forEach((element) {
        getRecordList.add(element);
      });
      getMyWigets=newGetMyWigets;
      getMyWigets.page=page;
      print("================当前页面${getMyWigets.page}");
      isLast=false;
      setState(() {
      });
    }else{
      isLast=true;
      setState(() {
      });
    }
  }

  ///单击画布的布局
  Widget MyChangeWidget(){
    print("-------------------调用了刷新数据--------------------$mm");
    return mm!=null?
    Container(
      child: CustomPaint(
        // size：当child为null时，代表默认绘制区域大小，如果有child则忽略此参数，画布尺寸则为child尺寸
        size: Size(
            (((MediaQuery.of(context).size.width -
                53.5 -
                21) /
                5) *
                (getRecordList.length>=5?getRecordList.length:5)),
            300),
        painter: MyChangeY(getRecordList, context,mm),
      ),
    ):Container();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: new Text('Flutter绘制虚线'),
          centerTitle: true,
        ),
        body: Stack(
          children: <Widget>[
            ///X轴
            Container(
              margin: EdgeInsets.only(left: 53.5 - 16, top: 32),
              // color: Colors.white,
              child: CustomPaint(
                // size：当child为null时，代表默认绘制区域大小，如果有child则忽略此参数，画布尺寸则为child尺寸
                size: Size(MediaQuery.of(context).size.width - 32 - 21, 224),
                painter: MyPainterX(getRecordList),
              ),
            ),

            ///X轴以及轴的点
            Container(
              width: MediaQuery.of(context).size.width - 53.5 - 21 - 21,
              margin: EdgeInsets.only(left: 53.5 + 21, top: 32),
              height: 268,
              alignment: Alignment.center,
              child: SingleChildScrollView(
                controller: scrollController,
                  scrollDirection: Axis.horizontal,
                  reverse: true,
                  child: Container(
                    width:
                        ((MediaQuery.of(context).size.width - 53.5 - 21) / 5) *
                            (getRecordList.length>=5?getRecordList.length:5),
                    height: 268,
                    child: Stack(
                      children: <Widget>[
                        ///X轴画布
                        Container(
                          child: CustomPaint(
                            // size：当child为null时，代表默认绘制区域大小，如果有child则忽略此参数，画布尺寸则为child尺寸
                            size: Size(
                                (((MediaQuery.of(context).size.width -
                                            53.5 -
                                            21) /
                                        5) *
                                    (getRecordList.length>=5?getRecordList.length:5)),
                                300),
                            painter: MyPainterY(getRecordList, context,mm),
                          ),
                        ),

                        MyChangeWidget(),

                        ///X轴点击事件
                        Container(
                          height: 226,
                          child: ListView.builder(
                            physics: NeverScrollableScrollPhysics(),
                            scrollDirection: Axis.horizontal,
                            reverse: true,
                            itemBuilder: (BuildContext context, int i) {
                              return GestureDetector(
                                onTap: () {
                                  print(
                                      "===================单击了$i=====================");
                                  mm=i;
                                  setState(() {
                                  });
                                },
                                child: zz(i),
                              );
                            },
                            itemCount: getRecordList.length,
                          ),
                        ),


                      ],
                    ),
                  )
              ),
            ),
          ],
        ));
  }
}

//画布Y坐标轴
class MyPainterX extends CustomPainter {
  MyPainterX(this.getRecordLists);

  //获取接口数据
  List<GetRecordLists> getRecordLists;

  //最大体重值
  double maxWeight;

  zz() {
    maxWeight = 0.0;
    for (int i = 0; i < getRecordLists.length; i++) {
      if (maxWeight < getRecordLists[i].weight) {
        maxWeight = getRecordLists[i].weight;
      }
      print("=============获取的数据${getRecordLists[i].weight}==============${getRecordLists[i].dateTime}");
    }
  }

  @override
  void paint(Canvas canvas, Size size) {
    ///获取最大的体重数
    zz();

    ///床架画笔
    var paint = Paint()
      ..strokeWidth = 1
      ..isAntiAlias = true // 是否抗锯齿
      ..color = Color.fromRGBO(153, 153, 153, 1);

    ///创建背景虚线
    var max = size.width - 16; // size获取到宽度
    //虚线之间的宽度
    var dashWidth = 5;
    var dashSpace = 5;
    //虚线X轴的初始值
    double startX = 37.5;
    //虚线循环之间的宽度
    final space = (dashSpace + dashWidth);

    //虚线显示
    while (startX < max) {
      for (var i = 0; i < 5; i++) {
        canvas.drawLine(Offset(startX, (i + 1) * 224 / 5),
            Offset(startX + dashWidth, (i + 1) * 224 / 5), paint);
      }
      startX += space;
    }

    ///初始值
    var startOffset = 20.5 - 16;

    ///Y轴
    for (int i = 0; i < 5; i++) {
      //绘制文字
      var textPainter = TextPainter(
        text: TextSpan(
            text: "${(((((maxWeight + 20) / 100).ceil()) * 100) / 4) * i}",
            style: TextStyle(
                color: Color.fromRGBO(153, 153, 153, 1), fontSize: 12)),
        textDirection: TextDirection.rtl,
      )..layout();
      textPainter.paint(canvas, Offset(startOffset, ((5 - i) * (224 / 5)) - 7));
    }
  }

  ///是否进行界面的重新刷新加载
  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}

//画布X坐标轴
class MyPainterY extends CustomPainter{
  MyPainterY(this.getRecordLists, this.context,this.mm);

  ///获取接口数据
  List<GetRecordLists> getRecordLists;
  BuildContext context;
  int mm;

  ///初始化折线坐标列表
  List<Offset> points = [];

  ///初始化起始坐标
  double startX = 37.5;

  ///初始化折线点
  var brokenLine = Paint()
    ..strokeWidth = 1.5
    ..isAntiAlias = true // 是否抗锯齿
    ..style = PaintingStyle.stroke
    ..color = Color.fromRGBO(255, 64, 89, 1);

  ///初始化两个画布
  var path1 = Path();
  var path = Path();

  ///初始值
  var startOffset = 20.5 - 16;

  @override
  void paint(Canvas canvas, Size size) {
    ///X轴
    for (int i = getRecordLists.length - 1; i >= 0; i--) {
      ///绘制X轴的文字显示
      List<String> zz = getRecordLists[i].dateTime.split("-");
      // 字符串截取
      // if(zz[1].startsWith("0")){
      //   zz[1]=zz[1].substring(1, 2);
      // }
      //绘制文字
      var textPainter = TextPainter(
        text: TextSpan(
            text: "${zz[1]}.${zz[2]}",
            style: TextStyle(
                color: Color.fromRGBO(153, 153, 153, 1), fontSize: 12)),
        textDirection: TextDirection.rtl,
      )..layout();

      ///X轴
      textPainter.paint(
          canvas,
          Offset(
              (((MediaQuery.of(context).size.width - 50 - 18) / 5) *
                      (getRecordLists.length - i - 1)) ,
              5 * (224 / 5) + 22));
      /// 绘制折线显示
      if (i == getRecordLists.length - 1) {
        path1.moveTo(
            (((MediaQuery.of(context).size.width - 50 - 2) / 5) *
                    (getRecordLists.length - i - 1)) +
                12,
            224-(((((224/5)*5)-(224/5))/100) * (getRecordLists[i].weight))
        );
      } else {
        path1.lineTo(
            (((MediaQuery.of(context).size.width - 50 - 2) / 5) *
                    (getRecordLists.length - i - 1)) +
                12,
            224-(((((224/5)*5)-(224/5))/100) * (getRecordLists[i].weight))
        );
      }
      ///绘制圆点
      points.add(Offset(
          (((MediaQuery.of(context).size.width - 50 - 2) / 5) *
                  (getRecordLists.length - i - 1)) +
              12,
          224-(((((224/5)*5)-(224/5))/100) * (getRecordLists[i].weight)))
      );

      ///绘制背景图片
      if (i == getRecordLists.length - 1) {
        path.moveTo(12, 5 * (224 / 5) + 22);
        path.lineTo(12, 224-(((((224/5)*5)-(224/5))/100) * (getRecordLists[i].weight)));
      } else if (i == 0) {
        path.lineTo(
            (((MediaQuery.of(context).size.width - 50 - 2) / 5) *
                    (getRecordLists.length - 0 - 1)) +
                12,
            224-(((((224/5)*5)-(224/5))/100) * (getRecordLists[i].weight)));
        path.lineTo(
            (((MediaQuery.of(context).size.width - 50 - 2) / 5) *
                    (getRecordLists.length - 0 - 1)) +
                12,
            5 * (224 / 5) + 22);
      } else {
        path.lineTo(
            (((MediaQuery.of(context).size.width - 50 - 2) / 5) *
                    (getRecordLists.length - i - 1)) +
                12,
            224-(((((224/5)*5)-(224/5))/100) * (getRecordLists[i].weight)));
      }
    }
    canvas.drawPath(path1, brokenLine);

    ///绘制背景色渐变
    //颜色渐变
    final rect = new Rect.fromLTWH(0.0, 0.0, size.width, size.height - 20);
    var gradient = new LinearGradient(
      begin: Alignment.topCenter,
      end: Alignment.bottomCenter,
      colors: [
        Color.fromRGBO(255, 64, 89, 1),
        Color.fromRGBO(255, 255, 255, 0.5)
      ],
    );
    //点
    var _paint2 = Paint()
      ..strokeWidth = 1.5
      ..isAntiAlias = true // 是否抗锯齿
      // ..style = PaintingStyle.stroke
      ..color = Colors.red
      ..shader = gradient.createShader(rect);

    ///绘制到画布
    canvas.drawPath(path, _paint2);

    ///绘制圆点
    //圆点
    var _paints = Paint()
      ..strokeWidth = 1.5
      ..isAntiAlias = true // 是否抗锯齿
      ..style = PaintingStyle.stroke
      ..color = Color.fromRGBO(255, 64, 89, 1);
    //圆点
    var _paints2 = Paint()
      ..strokeWidth = 1.5
      ..isAntiAlias = true // 是否抗锯齿

      ..color = Colors.white;

    for (int i = 0; i < points.length; i++) {
        canvas.drawCircle(points[i], 3.0, _paints2 //绘画风格改为stroke
        );
        canvas.drawCircle(points[i], 3.0, _paints //绘画风格改为stroke
        );
    }
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}

//点击的坐标
class MyChangeY extends CustomPainter {
  MyChangeY(this.getRecordLists, this.context,this.mm);

  ///获取接口数据
  List<GetRecordLists> getRecordLists;
  BuildContext context;
  int mm;

  ///初始化折线坐标列表
  List<Offset> points = [];



  @override
  void paint(Canvas canvas, Size size) {
    print("---------------------调用了--------------------");

    ///绘制圆点
    //圆点
    var _paints = Paint()
      ..strokeWidth = 1.5
      ..isAntiAlias = true // 是否抗锯齿
      ..color = Color.fromRGBO(255, 64, 89, 1);
    //圆点
    var _paints2 = Paint()
      ..strokeWidth = 1.5
      ..isAntiAlias = true // 是否抗锯齿
      ..style = PaintingStyle.stroke
      ..color = Colors.white;

    //X轴的初始值
    double changeX =(((MediaQuery.of(context).size.width - 50 - 2) / 5) *
        (getRecordLists.length - mm - 1)) +
        12;

    //X轴的初始值
    double changeY =224-(((((224/5)*5)-(224/5))/100) * (getRecordLists[mm].weight));

    //虚线之间的宽度
    var dashWidth = 5;
    var dashSpace = 5;
    //虚线循环之间的宽度
    final space = (dashSpace + dashWidth);
    var starY=224/5;

    //虚线显示
    while (starY <= ((224/5)*5)) {
      for (var i = 0; i < 5; i++) {
        canvas.drawLine(Offset(changeX,starY),
            Offset(changeX ,starY+dashWidth), _paints);
      }
      starY += space;
    }
    ///绘制圆点
    points.add(Offset(
      changeX,changeY
        )
    );
      canvas.drawCircle(points[0], 3.0, _paints2 //绘画风格改为stroke
      );
      canvas.drawCircle(points[0], 3.0, _paints //绘画风格改为stroke
      );
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}

